package cn.uncode.dal.asyn;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import cn.uncode.dal.datasource.DBContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.uncode.dal.core.BaseDAL;
import org.apache.commons.lang3.StringUtils;


/**
 * 分布异步任务
 * 
 * @author juny.ye
 */
public class ShardsBatchCallable implements Callable<Integer> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShardsBatchCallable.class);
    
    private final BaseDAL baseDAL;
    
    private final AsynContext context;
    
    public ShardsBatchCallable(BaseDAL baseDAL, AsynContext context){
    	this.baseDAL = baseDAL;
    	this.context = context;
    }
    
	@Override
	public Integer call() throws Exception {
		int total = 0;
		if(context.getObj() != null){
			if(StringUtils.isNotBlank(context.getDatabase())){
				DBContextHolder.swithTo(context.getDatabase());
			}
			if(context.getMethod().equals(Method.INSERT_BATCH)){
				List<Map<String, Object>> objs = (List<Map<String, Object>>) context.getObj();
				total = baseDAL.insertList(context.getTable(), objs);
			}else if(context.getMethod().equals(Method.UPDATE_BY_CRITERIA)){
				total = baseDAL.updateByCriteria(context.getObj(), context.getQueryCriteria());
			}else if(context.getMethod().equals(Method.DELETE_BY_CRITERIA)){
				total = baseDAL.deleteByCriteria(context.getQueryCriteria());
			}else if(context.getMethod().equals(Method.COUNT_BY_CRITERIA)){
				total = baseDAL.countByCriteria(context.getQueryCriteria());
			}
		}
    	return total;
	}
    
   

}
